package com.bienvenue.main.ui.activity.personal;

import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.afollestad.materialdialogs.MaterialDialog;
import com.bienvenue.main.R;
import com.bienvenue.main.adapter.OnlineResumePositionMoneyAdapter;
import com.bienvenue.main.adapter.OnlineResumeEducationBackgroundAdapter;
import com.bienvenue.main.adapter.OnlineResumePersonalStrengthAdapter;
import com.bienvenue.main.adapter.OnlineResumeProjectExperienceAdapter;
import com.bienvenue.main.adapter.OnlineResumeWorkExperienceAdapter;
import com.bienvenue.main.adapter.OnlineResumeSkillsCateListAdapter;
import com.bienvenue.main.base.BaseActivity;
import com.bienvenue.main.httpService.ResponseObserver;
import com.bienvenue.main.model.HttpBean;
import com.bienvenue.main.model.JobPostModel;
import com.bienvenue.main.model.ResumeInfoModel;
import com.bienvenue.main.model.SaveResumeModel;
import com.bienvenue.main.serviceApi.ServiceModel;
import com.bienvenue.main.ui.activity.enterprise.BusinessLicenseCertificationActivity;
import com.bienvenue.main.ui.activity.enterprise.PostJobActivity;
import com.bienvenue.main.utils.SPUtils;
import com.bienvenue.main.weight.LinesEditView;
import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.bigkoo.pickerview.view.TimePickerView;
import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;

import java.io.File;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.OnCheckedChanged;
import butterknife.OnClick;

/**
 * 　　　　　　　 ┏┓       ┏┓+ +
 * 　　　　　　　┏┛┻━━━━━━━┛┻┓ + +
 * 　　　　　　　┃　　　　　　 ┃
 * 　　　　　　　┃　　　━　　　┃ ++ + + +
 * 　　　　　　 █████━█████  ┃+
 * 　　　　　　　┃　　　　　　 ┃ +
 * 　　　　　　　┃　　　┻　　　┃
 * 　　　　　　　┃　　　　　　 ┃ + +
 * 　　　　　　　┗━━┓　　　 ┏━┛
 * ┃　　  ┃
 * 　　　　　　　　　┃　　  ┃ + + + +
 * 　　　　　　　　　┃　　　┃　Code is far away from     bug with the animal protecting
 * 　　　　　　　　　┃　　　┃ + 　　　　         神兽保佑,代码无bug
 * 　　　　　　　　　┃　　　┃
 * 　　　　　　　　　┃　　　┃　　+
 * 　　　　　　　　　┃　 　 ┗━━━┓ + +
 * 　　　　　　　　　┃ 　　　　　┣┓
 * 　　　　　　　　　┃ 　　　　　┏┛
 * 　　　　　　　　　┗┓┓┏━━━┳┓┏┛ + + + +
 * 　　　　　　　　　 ┃┫┫　 ┃┫┫
 * 　　　　　　　　　 ┗┻┛　 ┗┻┛+ + + +
 *
 * @ProjectName: Bienvenue
 * @Package: com.bienvenue.main.ui.activity
 * @ClassName: OnlineResumeActivity
 * @Description:在线简历
 * @Author: Mr.Chen
 * @UpdateUser: Mr.Chen
 * @UpdateDate: 2020/9/17
 * @UpdateRemark: 更新说明
 * @Version: 1.0
 */
public class OnlineResumeActivity extends BaseActivity {
    //项目经历
    @BindView(R.id.rv_project_experience)
    RecyclerView rvProjectExperience;
    //教育背景
    @BindView(R.id.rv_education_background)
    RecyclerView rvEducationBackground;
    //工作经历
    @BindView(R.id.rv_work_experience)
    RecyclerView rvWorkExperience;
    //个人特长
    @BindView(R.id.rv_personal_strength)
    RecyclerView rvPersonalStrength;
    //技能证书
    @BindView(R.id.rv_skills_certificate_list)
    RecyclerView rvSkillsCertificateList;
    @BindView(R.id.rv_position_money)
    RecyclerView rvPositionMoney;

    @BindView(R.id.iv_avatar)
    ImageView ivAvatar;
    @BindView(R.id.et_personal_name)
    EditText etPersonalName;
    @BindView(R.id.rg_gender)
    RadioGroup rgGender;
    @BindView(R.id.rb_man)
    RadioButton rbMan;
    @BindView(R.id.rb_woman)
    RadioButton rbWoman;
    @BindView(R.id.tv_job_searching_status)
    TextView tvJobSearchingStatus;
    @BindView(R.id.tv_date_of_birth)
    TextView tvDateOfBirth;
    @BindView(R.id.et_phone)
    EditText etPhone;
    @BindView(R.id.et_we_chat)
    EditText etWeChat;
    @BindView(R.id.et_email)
    EditText etEmail;
    @BindView(R.id.et_self_evaluation)
    LinesEditView etSelfEvaluation;

    String radioSelect;

    String userId;

    String avatarUrl;

    List<String> stringList = new ArrayList<>();


    MaterialDialog dialog;
    File file;

    OnlineResumeEducationBackgroundAdapter educationBackgroundAdapter;
    OnlineResumePersonalStrengthAdapter personalStrengthAdapter;
    OnlineResumeProjectExperienceAdapter projectExperienceAdapter;
    OnlineResumeWorkExperienceAdapter workExperienceAdapter;
    OnlineResumeSkillsCateListAdapter skillsCateListAdapter;
    OnlineResumePositionMoneyAdapter positionMoneyAdapter;
    ResumeInfoModel model;

    @Override
    protected void initData() {


    }

    @Override
    protected void initView() {
        rvEducationBackground.setLayoutManager(new LinearLayoutManager(this));
        rvPersonalStrength.setLayoutManager(new LinearLayoutManager(this));
        rvProjectExperience.setLayoutManager(new LinearLayoutManager(this));
        rvWorkExperience.setLayoutManager(new LinearLayoutManager(this));
        rvSkillsCertificateList.setLayoutManager(new GridLayoutManager(this, 4));
        rvPositionMoney.setLayoutManager(new LinearLayoutManager(this));

        educationBackgroundAdapter = new OnlineResumeEducationBackgroundAdapter();
        personalStrengthAdapter = new OnlineResumePersonalStrengthAdapter();
        projectExperienceAdapter = new OnlineResumeProjectExperienceAdapter();
        workExperienceAdapter = new OnlineResumeWorkExperienceAdapter();
        skillsCateListAdapter = new OnlineResumeSkillsCateListAdapter();
        positionMoneyAdapter = new OnlineResumePositionMoneyAdapter();


        rvEducationBackground.setAdapter(educationBackgroundAdapter);
        rvPersonalStrength.setAdapter(personalStrengthAdapter);
        rvProjectExperience.setAdapter(projectExperienceAdapter);
        rvWorkExperience.setAdapter(workExperienceAdapter);
        rvSkillsCertificateList.setAdapter(skillsCateListAdapter);
        rvPositionMoney.setAdapter(positionMoneyAdapter);

    }

    void onCheckChanged() {
        rgGender.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                radioSelect = selectRadioBtn(checkedId);
            }
        });

    }

    private String selectRadioBtn(int checkId) {
        RadioButton rbSelect = (RadioButton) findViewById(checkId);
        return rbSelect.getText().toString();
    }

    @Override
    protected void onResume() {
        super.onResume();
        userId = SPUtils.getString("userId");
        onCheckChanged();

        dialog = initDialog("请稍后...");
        ServiceModel.getServiceModel().getResumeInfo(userId, new ResponseObserver<ResumeInfoModel>() {
            @Override
            public void onSuccess(ResumeInfoModel response) {


                if (response.getCode() == 200) {
                    model = new ResumeInfoModel();
                    Glide.with(OnlineResumeActivity.this).load(response.getData().getUResumeInfo().get(0).getPhoto()).into(ivAvatar);

                    model.setCode(response.getCode());
                    model.setData(response.getData());
                    model.setMsg(response.getMsg());
                    model.getData().setUResumeCertificate(response.getData().getUResumeCertificate());
                    model.getData().setUResumeEducation(response.getData().getUResumeEducation());
                    model.getData().setUResumeExperience(response.getData().getUResumeExperience());
                    model.getData().setUResumeInfo(response.getData().getUResumeInfo());
                    model.getData().setUResumeJobhunting(response.getData().getUResumeJobhunting());
                    model.getData().setUResumeProgress(response.getData().getUResumeProgress());
                    model.getData().setUResumeWork(response.getData().getUResumeWork());
                    tvDateOfBirth.setText(response.getData().getUResumeInfo().get(0).getBirthday());
                    tvJobSearchingStatus.setText(response.getData().getUResumeInfo().get(0).getJobstatus());
                    etEmail.setText(response.getData().getUResumeInfo().get(0).getEmail());
                    etPersonalName.setText(response.getData().getUResumeInfo().get(0).getRealname());
                    etWeChat.setText(response.getData().getUResumeInfo().get(0).getWechat());
                    etPhone.setText(response.getData().getUResumeInfo().get(0).getPhone());
                    etSelfEvaluation.setContentText(response.getData().getUResumeInfo().get(0).getContent());
                    educationBackgroundAdapter.setNewData(response.getData().getUResumeEducation());
                    personalStrengthAdapter.setNewData(response.getData().getUResumeProgress());
                    projectExperienceAdapter.setNewData(response.getData().getUResumeExperience());
                    workExperienceAdapter.setNewData(response.getData().getUResumeWork());
                    skillsCateListAdapter.setNewData(response.getData().getUResumeCertificate());
                    positionMoneyAdapter.setNewData(response.getData().getUResumeJobhunting());
                    if (!TextUtils.isEmpty(response.getData().getUResumeInfo().get(0).getPhone())) {
                        etPhone.setFocusable(false);
                    } else {
                        etPhone.setFocusable(true);
                    }
                } else {
                    showLog(response.getMsg());
                }
            }

            @Override
            public void onFail(String message) {
                showLog(message);
            }
        });
        positionMoneyAdapter.setOnItemChildClickListener((adapter, view, position) -> {
            Intent intent = new Intent(OnlineResumeActivity.this, CareerObjectiveActivity.class);
            Bundle bundle = new Bundle();
            bundle.putInt("type", 1);
            bundle.putParcelable("positionMoney", positionMoneyAdapter.getData().get(position));
            intent.putExtras(bundle);
            startActivity(intent);
        });
        projectExperienceAdapter.setOnItemChildClickListener((adapter, view, position) -> {
            Intent intent = new Intent(OnlineResumeActivity.this, ProjectExperienceActivity.class);
            Bundle bundle = new Bundle();
            bundle.putInt("type", 1);
            bundle.putParcelable("projectExperience", projectExperienceAdapter.getData().get(position));
            intent.putExtras(bundle);
            startActivity(intent);
        });
        workExperienceAdapter.setOnItemChildClickListener((adapter, view, position) -> {
            Intent intent = new Intent(OnlineResumeActivity.this, WorkExperienceActivity.class);
            Bundle bundle = new Bundle();
            bundle.putInt("type", 1);
            bundle.putParcelable("workExperience", workExperienceAdapter.getData().get(position));
            intent.putExtras(bundle);
            startActivity(intent);
        });
        educationBackgroundAdapter.setOnItemChildClickListener((adapter, view, position) -> {
            Intent intent = new Intent(OnlineResumeActivity.this, EducationBackgroundActivity.class);
            Bundle bundle = new Bundle();
            bundle.putInt("type", 1);
            bundle.putParcelable("educationBackground", educationBackgroundAdapter.getData().get(position));
            intent.putExtras(bundle);
            startActivity(intent);
        });
        personalStrengthAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                Intent intent = new Intent(OnlineResumeActivity.this, PersonalStrengthActivity.class);
                Bundle bundle = new Bundle();
                bundle.putInt("type", 1);
                bundle.putParcelable("personalStrength", personalStrengthAdapter.getData().get(position));
                intent.putExtras(bundle);
                startActivity(intent);
            }
        });
        skillsCateListAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                ServiceModel.getServiceModel().deleteCertificate(skillsCateListAdapter.getData().get(position).getId(), new ResponseObserver<HttpBean>() {
                    @Override
                    public void onSuccess(HttpBean response) {
                        if (response.getCode() == 200 || response.getCode() == 0) {
                            skillsCateListAdapter.getData().remove(position);
                            showToast("删除成功");
                            skillsCateListAdapter.notifyDataSetChanged();
                        } else {
                            showToast(response.getMsg());
                        }
                    }

                    @Override
                    public void onFail(String message) {
                        showLog(message);
                    }
                });

            }
        });

    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_online_resume;
    }

    @OnClick(R.id.iv_return_btn)
    void onFinish() {
        this.finish();
    }

    @OnClick(R.id.iv_avatar)
    void onAvatar() {
        //参数很多，根据需要添加
        PictureSelector.create(OnlineResumeActivity.this)
                .openGallery(PictureMimeType.ofImage())// 全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio()
                .maxSelectNum(1)// 最大图片选择数量
                .minSelectNum(1)// 最小选择数量
                .imageSpanCount(4)// 每行显示个数
                .selectionMode(PictureConfig.MULTIPLE)// 多选 or 单选PictureConfig.MULTIPLE : PictureConfig.SINGLE
                .previewImage(true)// 是否可预览图片
                .isCamera(true)// 是否显示拍照按钮
                .isZoomAnim(true)// 图片列表点击 缩放效果 默认true
                //.setOutputCameraPath("/CustomPath")// 自定义拍照保存路径
                .enableCrop(false)// 是否裁剪
                .compress(true)// 是否压缩
                //.sizeMultiplier(0.5f)// glide 加载图片大小 0~1之间 如设置 .glideOverride()无效
                .glideOverride(160, 160)// glide 加载宽高，越小图片列表越流畅，但会影响列表图片浏览的清晰度
                .withAspectRatio(1, 1)// 裁剪比例 如16:9 3:2 3:4 1:1 可自定义
                //.selectionMedia(selectList)// 是否传入已选图片
                //.previewEggs(false)// 预览图片时 是否增强左右滑动图片体验(图片滑动一半即可看到上一张是否选中)
                //.cropCompressQuality(90)// 裁剪压缩质量 默认100
                //.compressMaxKB()//压缩最大值kb compressGrade()为Luban.CUSTOM_GEAR有效
                //.compressWH() // 压缩宽高比 compressGrade()为Luban.CUSTOM_GEAR有效
                //.cropWH()// 裁剪宽高比，设置如果大于图片本身宽高则无效
                .rotateEnabled(false) // 裁剪是否可旋转图片
                //.scaleEnabled()// 裁剪是否可放大缩小图片
                //.recordVideoSecond()//录制视频秒数 默认60s
                .forResult(PictureConfig.CHOOSE_REQUEST);//结果回调onActivityResult code
    }

    @OnClick(R.id.tv_job_searching_status)
    void onJobSearchIngStatus() {
        ServiceModel.getServiceModel().getListByWorkStatus(new ResponseObserver<JobPostModel>() {
            @Override
            public void onSuccess(JobPostModel response) {
                if (response.getCode() == 200) {
                    if (stringList != null && stringList.size() > 0) {
                        stringList.clear();
                    }
                    for (int i = 0; i < response.getData().size(); i++) {
                        stringList.add(response.getData().get(i).getVal());
                    }
                    OptionsPickerView pvOptions = new OptionsPickerBuilder(OnlineResumeActivity.this, new OnOptionsSelectListener() {
                        @Override
                        public void onOptionsSelect(int options1, int options2, int options3, View v) {
                            //返回的分别是三个级别的选中位置
                            tvJobSearchingStatus.setText(stringList.get(options1));

                        }
                    })
                            .setTitleText("请选择薪资")
                            .setDividerColor(Color.BLACK)
                            .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
                            .setContentTextSize(20)
                            .build();
                    pvOptions.setPicker(stringList);
                    pvOptions.show();

                } else {
                    showToast(response.getMsg());
                }
            }

            @Override
            public void onFail(String message) {
                Log.e("TAG", message);

            }
        });
    }

    @OnClick(R.id.tv_date_of_birth)
    void onDateOfBirth() {
        Calendar selectedDate = Calendar.getInstance();//系统当前时间

        Calendar startDate = Calendar.getInstance();
        startDate.set(1927, 1, 1);
        Calendar endDate = Calendar.getInstance();
        endDate.set(3019, 12, 31);
        TimePickerView timePicker = new TimePickerBuilder(this, new OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {
                tvDateOfBirth.setText(getTime(date));

            }
        })
                .setTitleText("请选择出生年月日")
                .setGravity(Gravity.BOTTOM)
                .setContentTextSize(18)
                .setTitleSize(20)
                .setDate(selectedDate)
                .setSubmitText("确定")
                .setCancelText("取消")
                .setRangDate(startDate, endDate)
                .build();
        timePicker.show();
    }

    @OnClick(R.id.iv_career_objective)
    void onCareerObjective() {
        //求职意向
        startActivity(new Intent(OnlineResumeActivity.this, CareerObjectiveActivity.class));
    }

    @OnClick(R.id.iv_project_experience)
    void onProjectExperience() {
        //项目经历
        startActivity(new Intent(OnlineResumeActivity.this, ProjectExperienceActivity.class));
    }

    @OnClick(R.id.iv_education_background_add)
    void onEducationBackgroundAdd() {
        //教育背景
        startActivity(new Intent(OnlineResumeActivity.this, EducationBackgroundActivity.class));
    }

    @OnClick(R.id.iv_work_experience_add)
    void onWorkExperienceAdd() {
        //工作经历
        startActivity(new Intent(OnlineResumeActivity.this, WorkExperienceActivity.class));
    }

    @OnClick(R.id.iv_personal_strength_add)
    void onPersonalStrengthAdd() {
        //个人评价
        startActivity(new Intent(OnlineResumeActivity.this, PersonalStrengthActivity.class));
    }

    @OnClick(R.id.iv_add_skills_certificate)
    void onAddSkillsCertificate() {
        //技能证书
        startActivity(new Intent(OnlineResumeActivity.this, SkillsCertificateActivity.class));
    }

    @OnClick(R.id.tv_enter_btn)
    void onEnter() {
        if (TextUtils.isEmpty(etPersonalName.getText().toString().trim()) || "".equals(etPersonalName.getText().toString().trim())) {
            showToast("请输入姓名");
            return;
        } else if ("请选择求职状态".equals(tvJobSearchingStatus.getText().toString().trim())) {
            showToast("请先选择求职状态");
            return;
        } else if ("请选择出生年月日".equals(tvDateOfBirth.getText().toString().trim())) {
            showToast("请选择出生年月");
            return;
        } else if (TextUtils.isEmpty(etPhone.getText().toString().trim()) || "".equals(etPhone.getText().toString().trim())) {
            showToast("请输入电话号码");
            return;
        }
//        else if (positionMoneyAdapter.getData()==null||positionMoneyAdapter.getData().size()==0){
//            showToast("请添加求职意向");
//            return;
//        }

        if (TextUtils.isEmpty(radioSelect)) {
            radioSelect = "男";
        }
        SaveResumeModel.ResumeInfoModel model = new SaveResumeModel.ResumeInfoModel();

        if (this.model != null || this.model.getData().getUResumeInfo().size() > 0) {
            model.setId(this.model.getData().getUResumeInfo().get(0).getId());
        }
        model.setBirthday(tvDateOfBirth.getText().toString().trim());
        model.setContent(etSelfEvaluation.getContentText().trim());
        model.setJobstatus(tvJobSearchingStatus.getText().toString().trim());
        model.setEmail(etEmail.getText().toString().trim());
        model.setPhoto(avatarUrl);
        model.setRealname(etPersonalName.getText().toString().trim());
        model.setUserid(userId);
        model.setSex(radioSelect);
        model.setWechat(etWeChat.getText().toString().trim());
        Gson gson=new Gson();
        String json=gson.toJson(model);
        showLog(json);

        ServiceModel.getServiceModel().putResumeInfo(model, new ResponseObserver<HttpBean>() {
            @Override
            public void onSuccess(HttpBean response) {
                if (response.getCode() == 200) {
                    showToast("保存成功");
                } else {
                    showToast(response.getMsg());
                }

            }

            @Override
            public void onFail(String message) {
                showLog(message);
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        List<LocalMedia> images = null;
        if (resultCode == RESULT_OK) {
            if (requestCode == PictureConfig.CHOOSE_REQUEST) {// 图片选择结果回调


                images = PictureSelector.obtainMultipleResult(data);
                file = new File(images.get(0).getPath());
                ivAvatar.setImageURI(Uri.fromFile(file));
                Log.e("TAG", "imgPath=>>>>" + file.getAbsolutePath());
                //selectList = PictureSelector.obtainMultipleResult(data);

                // 例如 LocalMedia 里面返回三种path
                // 1.media.getPath(); 为原图path
                // 2.media.getCutPath();为裁剪后path，需判断media.isCut();是否为true
                // 3.media.getCompressPath();为压缩后path，需判断media.isCompressed();是否为true
                // 如果裁剪并压缩了，以取压缩路径为准，因为是先裁剪后压缩的
                if (file == null && TextUtils.isEmpty(file.getAbsolutePath())) {
                    showToast("请重新选择图片");
                }
                MaterialDialog dialog = initDialog("请稍后...");


                dialog.show();
                ServiceModel.getServiceModel().setImg(file.getAbsolutePath(), new ResponseObserver<HttpBean>() {
                    @Override
                    public void onSuccess(HttpBean response) {
                        if (response.getCode() == 200) {
                            Log.e("TAG", "上传成功");
                            avatarUrl = response.getData().toString();
                            dialog.dismiss();

                        } else {
                            showToast("请重新确认图片格式");
                            dialog.dismiss();
                        }
                    }

                    @Override
                    public void onFail(String message) {
                        Log.e("TAG", message);
                        dialog.dismiss();
                    }
                });

            }
        }
    }
}
